<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/**
 * @author Меркулов Илья aka Bit0reZ
 * @license GNU GPLv3
 */

class Control extends CI_Controller {

        var $uid ; // UID in VVSU
        var $role ; // Role in VVSU
        var $maxParticipantCount = 60; // max users on Webinar
        var $base_url;
	var $env = ENVIRONMENT;
	var $stat;
	var $bbb_url;
	var $salt;

        function __construct()
	{
		parent::__construct();
		$this->load->config('eclass_cfg');
                $this->load->helper('data');
                $this->load->helper('url');
                $this->load->database('default');
                $this->load->library("session");
                $this->load->model('WebinarDB','wdb');
                $this->load->library('Webinar');
		$this->load->model('Webdb', 'webdb');
                $this->uid = $this->session->userdata('UID');
                $this->role = $this->session->userdata('role');
                $this->base_url = base_url();
		$this->bbb_url = $this->config->item('bbb_url');
		$this->salt = $this->config->item('salt');
        }

        function index()
        {
                show_404();
        }

	/*
	 * Login & Sesson data
	 */
	
        function login()
	{
		$this->load->library('jcryption');
		$this->load->model('Check', 'check');
		$Login = AesCtr::decrypt($_POST['username'], 'w3b1n4r', 256);
                $Pass = AesCtr::decrypt($_POST['passwd'], 'w3b1n4r', 256);
		if(strpos($Login, '\\') != 0){
			preg_match_all("|[\w]*|", $Login, $match); // cut domain
			$Login = $match[0][2];
		}
		$chk = '';
		$chk = $this->check->checkVVSUAccount($Login, $Pass, 'admin');
		if(is_array($chk))
                {
                        $this->set_userdata($chk);
                        $this->db_clean($chk['UID']);
                        $this->output->set_output(json_encode($chk));
                }
                else if(is_array($chk = $this->check->checkVVSUAccount($Login, $Pass, 'moderator', 3)))
                {
                        $this->set_userdata($chk);
                        $this->db_clean($chk['UID']);
                        $this->output->set_output(json_encode($chk));
                }
                else
                {
                        $chk = $this->check->checkVVSUAccount($Login, $Pass, 'attendee');
                        if(is_array($chk))
                        {
                                $this->set_userdata($chk);
                                $this->output->set_output(json_encode($chk));
                        }
                        else $this->output->set_output(json_encode(array('UID' => "$chk", 'login' => "$Login")));
                }
        }

        function logout()
        {
                $this->session->sess_destroy();
        }

        function set_userdata($data)
        {
                $this->session->set_userdata(array('UID' => $data['UID']));
                $this->session->set_userdata(array('surname' => $data['surname']));
                $this->session->set_userdata(array('firstname' => $data['firstname']));
                $this->session->set_userdata(array('secondname' => $data['secondname']));
                $this->session->set_userdata(array('role' => $data['role']));
        }

	/*
	 * BBB Control
	 */
	
        function create($pid = 0)
        {
                $this->seq();
                if($this->wdb->is_set($this->uid) == 0)
                {
                        if($pid == 0)
                        {
                                show_error('PID = 0!');
                        }
                        else
                        {
                                $this->load->library('BigBlueButton', null, 'bbb');
                                $meetingID = $this->wdb->create($this->uid, $pid);
                                $data = $this->wdb->plannedData($pid);
                                $welcome = 'Добро пожаловать!'."\n".'Тема: "'.$data['subj'].'".';
                                $mPW = sha1($meetingID.$this->uid.'webinar');
                                $aPW = sha1($meetingID.'attendee');
                                $count =  @$data['count'];
                                $SALT = @$this->salt;
                                $URL = @$this->bbb_url;
                                $username = $this->session->userdata('surname');
                                $logoutURL = base_url().'control/left/'.$meetingID;
                                $res = $this->bbb->createMeetingArray($username,
                                        $meetingID, $welcome, $mPW, $aPW, $SALT, $URL, $logoutURL);
                                redirect(base_url());
                        }
                }
                else
                {
                        show_error('More than one webinar running!');
                }
        }

        function add()
        {
                $this->seq();
                /*
                 * TODO: Рефакторинг функции добавления в PLANNED
                 */
                $this->load->helper('date');
                $data['uid'] = $this->uid;
                $data['date'] = $this->input->post('date');
                $data['stime'] = $this->input->post('startTime');
                $data['etime'] = $this->input->post('endTime');
                $data['count'] = $this->input->post('count');
                $data['userdata'] = $this->session->userdata('surname')." ".
                        substr($this->session->userdata('firstname'), 0, 2).".".
                        substr($this->session->userdata('secondname'), 0, 2).".";
                $data['subj'] = str_replace("\r\n", "", htmlspecialchars(urldecode($_POST['subj'])));
                $period = json_decode($this->input->post('period'), TRUE);
                $data['mails'] = $mails = $this->input->post('mails');
                $data['reply'] = $reply_to = $this->input->post('replyto');
		$data['status'] = $this->input->post('status');
                preg_match_all("((\d+)(?=[:]?))", $data['stime'], $matches);
                $stime = $matches[0][0] * 60 + $matches[0][1];
                preg_match_all("((\d+)(?=[:]?))", $data['etime'], $matches);
                $etime = $matches[0][0] * 60 + $matches[0][1];
                $plan = 0;
                /*if(isset($period['type']) &&($period['type'] != '0'))
                {
                        $sdate = $data['date'];
                        switch($period['type'])
                        {
                                case 'daily':
                                        while(strtotime($period['edate'])>=strtotime($sdate))
                                        {
                                                $data['date'] = $sdate;
                                                $plan = $this->wdb->plan($data, $this->maxParticipantCount);
                                                $sdate = mdate('%Y-%m-%d', strtotime($sdate)+100000);
                                        }
                                        //$plan = $this->wdb->plan($data, $this->maxParticipantCount);
                                        break;
                                case 'monthly':
                                        $day = mdate('%d', strtotime($sdate));
                                        $month = mdate('%m', strtotime($sdate));
                                        $year = mdate('%Y', strtotime($sdate));
                                        while(strtotime($period['edate'])>=strtotime($year.'-'.$month.'-'.$day))
                                        {
                                                if($month < 10) $month = '0'.$month;
                                                $data['date'] = $year.'-'.$month.'-'.$day;
                                                $plan = $this->wdb->plan($data, $this->maxParticipantCount);
                                                ($month < 12) ? $month++ : $month=1;
                                        }
                                        break;
                                case 'weekly':
                                        preg_match_all('|\w+\s|', $period['days'], $matches);
                                        $day = mdate('%d', strtotime($sdate));
                                        $month = mdate('%m', strtotime($sdate));
                                        $year = mdate('%Y', strtotime($sdate));
                                        while(strtotime($period['edate'])>=strtotime($year.'-'.$month.'-'.$day))
                                        {
                                                foreach ($matches[0] as $key => $val)
                                                {
                                                        if(mdate('%D', strtotime($year.'-'.$month.'-'.$day)) == substr($val,0,3))
                                                        {
                                                                $plan = $this->wdb->plan($data, $this->maxParticipantCount);
                                                        }
                                                }
                                                if($day < days_in_month($month, $year)) $day++;
                                                else
                                                {
                                                        $day = 1;
                                                        $month++;
                                                }
                                        }
                                        break;
                        }
                }
                else
                {*/
                        $plan = $this->wdb->plan($data, $this->maxParticipantCount);
                //}
                if($plan > 0)
                {
                        if(isset($mails) && $mails !='')
                        {
                                $this->load->library('Parser');
                                preg_match_all('([\w-\.]+@[\w\.]+(?:\.+[(ru)(net)(org)(com)(info)]+))', $mails, $matches);
                                $mails = '';
                                foreach($matches as $key => $val)
                                {
                                        foreach($val as $mail)
                                        {
                                                $mails .= $mail.', ';
                                        }
                                }
                                $data['base_url'] = $this->base_url;
                                $message  = $this->parser->parse('messages/email.html', $data, true);
                                $bool = $this->webinar->mail($mails, "\"Вебинар ВГУЭС. ".$data['subj']."\"", $message, $reply_to);
                        }
			if($data['status'] == 1)
			{
				$data['id'] = $plan;
				$data['subj'] = iconv('utf8','cp1251', $data['subj']);
				$this->webdb->addObj($data);
			}
                        $this->output->append_output(json_encode(array("res" => "success")));
                }
                else
                {
                        $this->output->append_output(json_encode(array("res" => "error",
                            "message" => "Невозможно запланировать вебинар с такими данными!".
                            "\n"."Возможно вебинар с такими данными уже запланирован или количесво участников".
                            "\n"."превысило допустимый порог.")));
                }
        }

        function copy()
        {
		$this->load->library('Parser');
                $date = $this->input->post('date');
                $id = $this->input->post('id');
                $this->db->select('subj, date, stime, etime, count, userdata, mails, reply');
                $this->db->from('past');
                $this->db->where('id', $id);
                $this->db->where('UID', $this->uid);
                $query = $this->db->get();
                $data = $query->result_array();
                $data[0]['date'] = $date;
                $data[0]['uid'] = $this->uid;
                $plan = $this->wdb->plan($data[0], $this->maxParticipantCount);
                if($plan > 0)
                {
			$this->webdb->actObj($plan);
			$data[0]['base_url'] = @$this->base_url;
			$reply_to = $data[0]['reply'];
			$mails = $data[0]['mails'];
                        $message  = $this->parser->parse('messages/email.html', $data[0], true);
                        $bool = $this->webinar->mail($mails, "\"Вебинар ВГУЭС. ".$data[0]['subj']."\"", $message, $reply_to);
			$this->output->append_output(json_encode(array("res" => "success")));
                }
                else
                {
                        $this->output->append_output(json_encode(array("res" => "error",
                            "message" => "Невозможно запланировать вебинар с такими данными!".
                            "\n"."Возможно вебинар с такими данными уже запланирован или количесво участников".
                            "\n"."превысило допустимый порог.")));
                }
                /*
                 * TODO: Дописать копирование.
                 */
        }

        function edit()
        {
                $data = $this->wdb->planned($this->uid);
                $this->output->append_output(json_encode($data));
        }

        function save($id)
        {
		$this->load->library('Parser');
                $data['date'] = $this->input->post('date');
                //$data['date'] = mdate('%Y-%m-%d',mysql_to_unix($data['date']));
                preg_match_all('/(\d{2}).(\d{2}).(\d{4})/', $data['date'], $match);
                if($match[0] != array()) $data['date'] = $match[3][0].'-'.$match[2][0].'-'.$match[1][0];
                $data['stime'] = $this->input->post('stime');
                $data['etime'] = $this->input->post('etime');
                $data['count'] = $this->input->post('count');
                $data['subj'] = htmlspecialchars(urldecode($this->input->post('subj')));
		$data['reply'] = $this->input->post('reply');
		$data['mails'] = $this->input->post('mails');
		$data['status'] = $this->input->post('status');
		$dt = $this->wdb->plannedData($id);
		$this->wdb->update($id, $data);
		
		unset($data['count']);
		$data['base_url'] = @$this->base_url;
		$data['userdata'] = $this->session->userdata('surname')." ".
                        substr($this->session->userdata('firstname'), 0, 2).".".
                        substr($this->session->userdata('secondname'), 0, 2).".";
		$message  = $this->parser->parse('messages/changes.html', $data, true);
		$bool = $this->webinar->mail($data['mails'], "\"Вебинар ВГУЭС (изменение). ".$data['subj']."\"", $message, $data['reply']);
		
		if($data['status'] != $dt['status'])
			switch($data['status'])
			{
				case '0': $this->webdb->delObj($id);
					break;
				case '1': $data['id'] = $id;
					$data['subj'] = iconv('utf8', 'cp1251', $data['subj']);
					$this->webdb->addObj($data);
					break;
			}
                $this->output->append_output(json_encode(array("res" => "success")));
                //print_r($match);
	}

	function printf($data, $ctrl)
	{
		if($ctrl == 1)
		{
			$this->output->append_output(json_encode($data));
		}
		else
		{
			if(isset($data['error']))
				show_error('Ошибка!: '.$data['error']);
			else
				$this->output->append_output($data['message']);
		}

	}
	
	function join($id)
	{
		$ctrl = $this->input->post('ctrl');
		if(!isset($id)) $this->printf(array('error' => 'Такой комнаты нет!'));
                $this->load->library('BigBlueButton', null, 'bbb');
                $running = $this->wdb->is_running($id);
                $mPW = sha1($id.$this->wdb->getUID($id).'webinar');
                if($running)
                {
                        $URL = @$this->bbb_url;
                        $SALT = @$this->salt;
                        $MeetingInfo = $this->bbb->getMeetingInfoArray($id, $mPW, $URL, $SALT);
			$name = $this->session->userdata('surname').' '.
                                        $this->session->userdata('firstname');
			if($this->webinar->isInMeeting($id, $name, $mPW, $URL, $SALT))
			{
				$this->printf(array('error' => 'Пользователь с таким именем уже присутствует в конференции!'));
			}
                        else if($MeetingInfo['participantCount'] < $this->wdb->maxParticipantCount($id))
                        {
                                //$name = $this->session->userdata('surname').' '.
                                  //      $this->session->userdata('firstname');
                                $own = $this->wdb->own($this->uid, $id);
                                if($own || $this->role == 'admin')
                                {
                                        $PW = @$mPW;
                                }
                                else
                                {
                                        $PW = sha1($id.'attendee');
                                }
				$this->load->helper('date');
				$data['wbid'] = @$id;
				$data['UID'] = @$this->uid;
				$data['intime'] = mdate('%H:%i:%s',time());
				$data['outtime'] = '';
				$data['uname'] = @$name;
				$data['ip'] = $this->session->userdata('ip_address');
				$this->wdb->join($data);
				if($ctrl == 1)
					$this->printf(array('url' => $this->bbb->joinURL($id, $name, $PW, $SALT, $URL)));
				else
                                	redirect($this->bbb->joinURL($id, $name, $PW, $SALT, $URL));
                        }
                        else
                        {
                                redirect(base_url());
                        }
                }
                else
                {
                        redirect(base_url());
                }
        }
	
	function left($id)
	{
		$this->wdb->left($id, $this->uid);
		redirect($this->base_url);
	}

        function end($id, $adm = null)
        {
                if($this->wdb->is_running($id))
                {
                        if($this->wdb->own($this->uid, $id) || ($this->role == 'admin' && $adm != null))
                        {
                                $this->load->library('BigBlueButton', null,'bbb');
                                $salt = $this->salt;
                                $url = $this->bbb_url;
                                $pw = sha1($id.$this->uid.'webinar');
				$data = $this->wdb->plannedData($id);
				$this->webdb->endObj($id);
                                $this->wdb->end($id);
                                $res = $this->bbb->endMeeting($id, $pw, $url, $salt);
                        }
                        else
                        {
				
                        }
                }
                redirect(base_url());
        }

	/*
	 * Info
	 */

	function planned($par = '')
        {
                $this->load->helper('date');
                $date = $this->input->post('date');
		//$time = $this->input->post('time');
                ($par == 'all')? $all = true : $all = false;
                if($date == '') $date = mdate('%Y-%m-%d', now());
                $data = $this->wdb->planned($this->uid, $all, $date);
                array_change_key_case($data);
                $this->output->append_output(json_encode($data));
        }
	
        function past($par = '')
        {
                $date = $this->input->post('date');
		$group = $this->input->post('group');
		$from = $this->input->post('from');
                //if($date != '') $date =
                ($par == 'all')? $all = true : $all = false;
                $data = $this->wdb->past($this->uid, $all, $date, $group, $from);
		//foreach($data as $key => $val) $data[$key]['control'] = 1;
                $this->output->append_output(json_encode($data));
        }
        
        function owned($id)
        {
                if($this->wdb->own($this->uid, $id))
                {
                        $this->output->append_output('{"res": "success"}');
                }
                else
                {
                        $this->output->append_output('{"res": "error", "message": ""}');
                }
        }

        function now_running()
        {
                $this->load->library('BigBlueButton', NULL, 'bbb');
                $this->load->library('Parser');
		$this->load->model('Check', 'check');
                $data['base_url'] = @$this->base_url;
                $data['url'] = @$this->bbb_url;
                $data['salt'] = @$this->salt;
                $data['UID'] = @$this->uid;
                $data['role'] = @$this->role;
                $data['webinar'] = $this->webinar->now_running($data['url'], $data['salt']);

		if(!$data['webinar']) $data['message'][0] = array('text' => "На данный момент вебинаров не проводится.");
		else $data += array('message' => array()); // TODO: And Fix IT!

                $this->parser->parse('templates/nowRunning.html', $data);
        }

        /*function calendar()
        {
                $this->load->library('Parser');
                $this->parser->parse('templates/calendar.html', $data);
        }*/
	
	/*
	 * Additional func
	 */

        function seq($role = 'moderator', $obj = 'null', $show = true)
        {
                if($this->uid == FALSE){
			if($show) show_error('You are not logged in.', '401');
			return 1;
		}
                if($this->role != $role && $this->role != 'admin'){
			if($show) show_error('You are not moderator.');
			return 1;
		}
		return 0;
                /*else if(!$this->obj)
                {
                        show_error();
                }*/
        }

        function db_clean($UID = 0)
        {
                /*
                 * TODO: Довести все до нормального вида... (очистка)
                 */
                $this->load->helper('date');
                
                $this->db->select('ID');
                $this->db->from('planned');
                $this->db->where('UID', $UID);
                $this->db->where('date <', mdate('%Y-%m-%d',time()));
                $query = $this->db->get();
                $data = $query->result_array();
                foreach($data as $row)
			$this->db->query('call end('.$row['ID'].')');
        }

        function feedback()
        {
		if(true){//!$this->seq('', '', false)){
			$this->load->helper('date');
			$this->load->model('check');
			$this->load->library('Parser');
			$data['title'] = urldecode($this->input->post('title'));
			$data['text'] = urldecode($this->input->post('text'));
			$data['replyto'] = urldecode($this->input->post('replyto'));
			$data['type'] = $this->input->post('type');
			$data['date'] = mdate('%Y-%m-%d', now());
			$data['status'] = '1';
			$data['UID'] = @$this->uid;
			$id = $this->wdb->add_issue($data);
			if(isset($data['type'])){
				$data['id'] = @$id;
				$data['type'] = $this->wdb->getTypeByID($data['type']);
				if($this->uid != false)$data['user'] = $this->check->getUserByID($this->uid);
				else $data['user'] = array(array('surname' =>'guest'), array('firstname' =>''), array('secondname' =>''));
				$msg = $this->parser->parse('messages/new_issue.html', $data, true);
				$msg2 = $this->parser->parse('messages/new_error.html', $data, true);
				$this->webinar->mail($this->config->item('codermail'), 'New issue "'.$data['type'].'": '.$data['title'], $msg);
				if($this->env == 'production')
					$this->webinar->mail($this->config->item('managermail'), 'Вебинары '.$data['title'].' '.$data['user'].' '.$data['replyto'], $msg2);
			}
			$this->output->append_output(json_encode(array('res' => 'success')));
		}
		else{
			$this->output->append_output(json_encode(array('res' => 'error', 'title' => 'Вы не авторизованы!',
				'text' => 'Вам необходимо авторизоваться перед отправкой сообщения.')));
		}
        }

        function test($id = 0)
        {
		if($this->env == 'development')
		{
			/*$data['id'] = 2;
			$data['subj'] = iconv('utf8', 'cp1251','Rights');
			$this->webdb->addObj($data);
			 */
			//$this->webdb->delObj($id);
			$this->load->library('BigBlueButton', null, 'bbb');
			$mPW = sha1($id.$this->wdb->getUID($id).'webinar');
                        $URL = @$this->bbb_url;
                        $SALT = @$this->salt;
			$name = $this->session->userdata('surname').' '.
                                        $this->session->userdata('firstname');
			$this->webinar->isInMeeting($id, $name, $mPW, $URL, $SALT);
			/*
			$this->load->model('Check', 'check');
			print_r($this->check->checkVVSUAccount('Binar', 't3st3r', 'moderator'));
			 */
		}
		else
		{
			show_404();
		}
        }

        function phpinfo()
        {
		if($this->env == 'development')
		{
			echo phpinfo();
		}
		else
		{
			show_404();
		}
	}
}
